package cz.mtq.mgsc;

import java.util.Hashtable;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import cz.mtq.mgsc.model.Players;
import cz.mtq.mgsc.view.GameOptionsScreen;

/**
 * 
 * <a href="http://minigolfscorecard.googlecode.com/">MiniGolf Scorecard</a>
 * 
 * @author Miroslav Tichý
 *
 */
public class MgscMidlet extends MIDlet implements CommandListener {

	private final Players players = new Players();

	private final Hashtable commands = new Hashtable(4);

	protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
	}

	protected void pauseApp() {
	}

	protected void startApp() throws MIDletStateChangeException {
		com.sun.lwuit.Display.init(this);
		Settings.setResoureBundleLocale(Settings.getDefaultLocale(this));
		new GameOptionsScreen(this).setPlayersScreen();
	}

	public void addCommand(Displayable displayable, cz.mtq.mgsc.command.AbstractCommand cmd) {
		Command command = cmd.getCommand();
		// add command to displayable
		displayable.addCommand(command);
		// save the command for later execution
		this.commands.put(command, cmd);
	}

	public void removeCommand(Displayable displayable, cz.mtq.mgsc.command.AbstractCommand cmd) {
		Command command = cmd.getCommand();
		this.commands.remove(command);
		displayable.removeCommand(command);
	}

	public cz.mtq.mgsc.command.AbstractCommand getCommand(Command command) {
		return (cz.mtq.mgsc.command.AbstractCommand) commands.get(command);
	}

	public void commandAction(Command c, Displayable d) {
		cz.mtq.mgsc.command.AbstractCommand cmd = getCommand(c);
		if (cmd != null) {
			cmd.setDisplayable(d);
			try {
				cmd.execute();
			} catch (Exception e) {
				// TODO show an alert?
				e.printStackTrace();
			}
		}
	}

	public void setCurrent(Displayable displayable) {
		Display.getDisplay(this).setCurrent(displayable);
	}

	public Players getPlayers() {
		return players;
	}

	public void sortPlayers() {
		players.sortPlayers();
	}

	public void callSerially(Runnable thread) {
		Display.getDisplay(this).callSerially(thread);
	}
}
